package com.uphone.magicleafteacher.pro.activity.courselivecreate;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.blankj.utilcode.util.ToastUtils;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.radish.baselibrary.Intent.IntentData;
import com.radish.baselibrary.Intent.IntentUtils;
import com.radish.baselibrary.dialog.RadishDialog;
import com.radish.framelibrary.view.glide.GlideUtils;
import com.uphone.magicleafteacher.MainActivity;
import com.uphone.magicleafteacher.R;
import com.uphone.magicleafteacher.base.OnPermissionCallBack;
import com.uphone.magicleafteacher.base.mvp.BaseMvpActivity;
import com.uphone.magicleafteacher.datepicker.CustomDatePicker;
import com.uphone.magicleafteacher.datepicker.DateFormatUtils;
import com.uphone.magicleafteacher.pro.activity.AdviserActivity;
import com.uphone.magicleafteacher.pro.activity.StudentClassActivity;
import com.uphone.magicleafteacher.pro.activity.StudentRankActivity;
import com.uphone.magicleafteacher.util.CheckButton;
import com.uphone.magicleafteacher.util.CommonUtil;
import com.uphone.magicleafteacher.util.DialogUtils;
import com.uphone.magicleafteacher.util.GsonUtils;
import com.uphone.magicleafteacher.util.PictureSelectUtils;
import com.uphone.magicleafteacher.vo.CourseLiveEditBackBean;
import com.uphone.magicleafteacher.vo.TeacherLiveBean;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 创建直播课程
 * Time: 2019/10/29
 */
public class CourseLiveCreateActivity extends BaseMvpActivity<CourseLiveCreatePresenter> implements CourseLiveCreateContract.View {

    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.tv_time_start)
    TextView tvTimeStart;
    @BindView(R.id.ll_time_start)
    LinearLayout llTimeStart;
    @BindView(R.id.tv_time_end)
    TextView tvTimeEnd;
    @BindView(R.id.ll_time_end)
    LinearLayout llTimeEnd;
    @BindView(R.id.tv_prepare)
    TextView tvPrepare;
    @BindView(R.id.ll_time_prepare)
    LinearLayout llTimePrepare;
    @BindView(R.id.tv_level)
    TextView tvLevel;
    @BindView(R.id.tv_num)
    TextView tvNum;
    @BindView(R.id.ll_time_level)
    LinearLayout llTimeLevel;
    @BindView(R.id.tv_class)
    TextView tvClass;
    @BindView(R.id.ll_time_class)
    LinearLayout llTimeClass;
    @BindView(R.id.iv_pic)
    ImageView ivPic;
    @BindView(R.id.btn_submit)
    CheckButton btnSubmit;
    @BindView(R.id.btn_delete)
    TextView btnDelete;
    @BindView(R.id.btn_save)
    CheckButton btnSave;
    @BindView(R.id.ll_submit)
    LinearLayout llSubmit;
    private CustomDatePicker mTimerPicker, mEndPicker;
    private String ran;
    private String clas;
    private String beginTimeStr;
    private String prepareTime;
    @IntentData
    private int liveId;
    private String picUrl;

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    protected void initBundle() {

    }

    @Override
    protected int initLayout() {
        return R.layout.activity_course_live_create;
    }

    @Override
    protected void initView() {
        CheckButton button = btnSubmit;

        if (liveId != 0) {
            btnSubmit.setVisibility(View.GONE);
            llSubmit.setVisibility(View.VISIBLE);
            etName.setEnabled(false);
            button = btnSave;
            mPresenter.liveClassInfo(liveId);
        } else {
            btnSubmit.setVisibility(View.VISIBLE);
            llSubmit.setVisibility(View.GONE);
        }
        button.addCountNum(1);
        button.setRelaViews(new CheckButton.ChangeCallback() {
            @Override
            public void click(boolean enable) {
                if (enable) {
                    if (liveId != 0) {//编辑
                        if (workPic != null && !TextUtils.isEmpty(workPic.getPath())) {
                            File file = new File(workPic.getPath());
                            if (file.exists()) {
                                mPresenter.uploadImgFile(file,
                                        liveId, classSelectBackId, rankSelectBackId);
                                return;
                            }
                        }
                        mPresenter.editLiveClass(liveId, classSelectBackId, rankSelectBackId, picUrl);
                    } else {//创建
                        if (workPic == null) {
                            ToastUtils.showShort("请选择封面");
                            return;
                        }
                        File file = new File(workPic.getPath());
                        if (file == null || !file.exists()) {
                            ToastUtils.showShort("请选择封面");
                            return;
                        }
                        mPresenter.uploadImgFile(file,
                                etName.getText().toString().trim(), tvTimeStart.getText().toString().trim(),
                                tvTimeEnd.getText().toString().trim(), prepareTime,
                                rankSelectBackId, classSelectBackId);
                    }
                } else {
                    ToastUtils.showShort("请完善信息");
                }
            }
        }, etName, tvTimeStart, tvTimeEnd, tvPrepare, tvLevel, tvClass);


        initTimerPicker();
    }

    @Override
    protected void initTitle() {
        initTitle("新建直播");
    }

    @Override
    protected void initData() {


    }

    //直播准备
    private void showBottomDialog() {
        //1、使用Dialog、设置style
        final Dialog dialog = new Dialog(this, R.style.DialogTheme);
        //2、设置布局
        View view = View.inflate(this, R.layout.dialog_prepare_layout, null);
        dialog.setContentView(view);
        Window window = dialog.getWindow();
        //设置弹出位置
        window.setGravity(Gravity.BOTTOM);
        //设置弹出动画
        window.setWindowAnimations(R.style.main_menu_animStyle);
        //设置对话框大小
        window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.show();

        dialog.findViewById(R.id.text_five).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                prepareTime = "5";
                tvPrepare.setText("用户可以提前5分钟进直播间");
                dialog.dismiss();
            }
        });

        dialog.findViewById(R.id.text_ten).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                prepareTime = "10";
                tvPrepare.setText("用户可以提前10分钟进直播间");
                dialog.dismiss();
            }
        });

        dialog.findViewById(R.id.text_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });

    }

    //选择时间
    private void initTimerPicker() {
        String beginTime = DateFormatUtils.long2Str(System.currentTimeMillis(), true);
        String endTime = "2070-12-31 08:00";

        tvTimeStart.setText(DateFormatUtils.long3Str(System.currentTimeMillis()));

        // 通过日期字符串初始化日期，格式请用：yyyy-MM-dd HH:mm
        mTimerPicker = new CustomDatePicker(this, new CustomDatePicker.Callback() {
            @Override
            public void onTimeSelected(long timestamp) {
                beginTimeStr = DateFormatUtils.long2Str(timestamp, true);
                tvTimeStart.setText(DateFormatUtils.long3Str(timestamp));
                tvTimeEnd.setText("");
            }
        }, beginTime, endTime);
        // 允许点击屏幕或物理返回键关闭
        mTimerPicker.setCancelable(true);
        // 显示时和分
        mTimerPicker.setCanShowPreciseTime(true);
        // 允许循环滚动
        mTimerPicker.setScrollLoop(true);
        // 允许滚动动画
        mTimerPicker.setCanShowAnim(true);
    }

    //结束时间
    private void endTimerPicker() {
        String beginTime = "";
        if (TextUtils.isEmpty(beginTimeStr)) {
            beginTime = DateFormatUtils.long2Str(System.currentTimeMillis(), true);
        } else {
            beginTime = beginTimeStr;
        }
        String endTime = "2070-12-31 08:00";

        tvTimeEnd.setText(tvTimeStart.getText().toString().trim());

        // 通过日期字符串初始化日期，格式请用：yyyy-MM-dd HH:mm
        mEndPicker = new CustomDatePicker(this, new CustomDatePicker.Callback() {
            @Override
            public void onTimeSelected(long timestamp) {
                tvTimeEnd.setText(DateFormatUtils.long3Str(timestamp));
            }
        }, beginTime, endTime);
        // 允许点击屏幕或物理返回键关闭
        mEndPicker.setCancelable(true);
        // 显示时和分
        mEndPicker.setCanShowPreciseTime(true);
        // 允许循环滚动
        mEndPicker.setScrollLoop(true);
        // 允许滚动动画
        mEndPicker.setCanShowAnim(true);
        mEndPicker.show(tvTimeEnd.getText().toString());
    }

    @Override
    protected void initListener() {
        etName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                tvNum.setText(s.toString().length() + "/15");
            }
        });
    }

    @OnClick({R.id.ll_time_start, R.id.ll_time_end, R.id.ll_time_prepare, R.id.ll_time_level, R.id.ll_time_class, R.id.iv_pic, R.id.btn_delete})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            //开课时间
            case R.id.ll_time_start:
                if (liveId == 0)
                    mTimerPicker.show(tvTimeStart.getText().toString());
                break;
            //结束时间
            case R.id.ll_time_end:
                if (liveId == 0)
                    endTimerPicker();
                break;
            //直播准备
            case R.id.ll_time_prepare:
                if (liveId == 0)
                    showBottomDialog();
                break;
            //学生级别
            case R.id.ll_time_level:
                IntentUtils.getInstance().with(this, StudentRankActivity.class).putInt("selectId", rankSelectBackId).start(100);
                break;
            //学生班级
            case R.id.ll_time_class:
                if (rankSelectBackId <= 0) {
                    ToastUtils.showShort("请先选择学生级别");
                    return;
                }
                IntentUtils.getInstance().with(this, StudentClassActivity.class)
                        .putInt("gradeId", rankSelectBackId)
                        .putInt("selectId", classSelectBackId)
                        .start(101);
                break;
            case R.id.iv_pic:
                //选择图片
                selectPic();
                break;
            case R.id.btn_delete:
                DialogUtils.alterDialog(this, "确定删除？", (dialog, view1, type) -> {
                    mPresenter.delLiveClass(liveId);
                });
                break;
        }
    }

    private String getTimes(Date date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }

    private int maxNum = 1;
    private LocalMedia workPic;

    private void selectPic() {
        getPermission(new OnPermissionCallBack() {
            @Override
            public void permissionPass(String[] permissions) {
                PictureSelectUtils.openMultiplePicture(CourseLiveCreateActivity.this, new ArrayList<>()
                        , maxNum, false, 0, 0, PictureConfig.CHOOSE_REQUEST);
            }

            @Override
            public void permissionRefuse(String[] permissions) {

            }
        }, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }

    @IntentData
    private int rankSelectBackId;
    @IntentData
    private int classSelectBackId;
    @IntentData
    private String rankSelectBackName;
    @IntentData
    private String classSelectBackName;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 100:// 学生级别
                tvLevel.setText(CommonUtil.getStr(rankSelectBackName));
                tvClass.setText("");
                classSelectBackId = 0;
                break;
            case 101:// 学生班级
                tvClass.setText(CommonUtil.getStr(classSelectBackName));
                break;
            case PictureConfig.CHOOSE_REQUEST:
                // 图片、视频、音频选择结果回调
                List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                if (selectList != null && selectList.size() > 0) {
                    workPic = selectList.get(0);
                    GlideUtils.getInstance().loadNormalImage(this, workPic.getPath(), ivPic);
                    btnSubmit.add();
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void liveClassInfo(String json) {
        CourseLiveEditBackBean bean = GsonUtils.getGson().fromJson(json, CourseLiveEditBackBean.class);
        if (bean != null && bean.getLiveClassInfo() != null) {
            rankSelectBackId = bean.getLiveClassInfo().getGradeId();
            classSelectBackId = bean.getLiveClassInfo().getClassId();
            picUrl = bean.getLiveClassInfo().getFacePic();
            etName.setText(CommonUtil.getStr(bean.getLiveClassInfo().getClassName()));
            tvNum.setText(CommonUtil.getStr(bean.getLiveClassInfo().getClassName()).length() + "/15");
            tvLevel.setText(CommonUtil.getStr(bean.getLiveClassInfo().getGradeName()));
            tvClass.setText(CommonUtil.getStr(bean.getLiveClassInfo().getClassName()));
            tvTimeStart.setText(CommonUtil.getStr(bean.getLiveClassInfo().getStartTime()));
            tvTimeEnd.setText(CommonUtil.getStr(bean.getLiveClassInfo().getEndTime()));
            tvPrepare.setText(CommonUtil.getStr("用户可以提前" + bean.getLiveClassInfo().getAheadCount() + "分钟进直播间"));
            GlideUtils.getInstance().loadNormalImage(this, CommonUtil.getImageUrl(bean.getLiveClassInfo().getFacePic()), ivPic);
        }
    }
}
